<template>
	<view>
		<view class="u-demo-block__content" style="margin: 16rpx;">
			<view class="u-page__tag-item">
				<u-search v-model="queryKey" 
					placeholder="请输入成品编码或名称、物料编码或名称"
					@custom="queryByParam"
					@search="queryByParam"></u-search>
			</view>
		</view>
		<view>
			<u-tabs
				@click="tabClick"
				:list="list1"
				lineWidth="90"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 20px; padding-right: 15px; height: 34px;">
			</u-tabs>
		</view>
		<view class="card-container" style="margin-bottom: 65px;">
			<view class="card-wrap">
				<view class="card-item">
					<uni-section class="mb-10" :title="`订单合同: ${contractCode}`" type="line"></uni-section>
				</view>
				<view class="card-item">
					选择仓库：
					<uni-easyinput type="text" v-model="stockSelectedStockNo" @focus="batchLoadStockList()" placeholder="选择仓库" size="mini" style="margin-right: 4px;"/>
					<button class="uni-button" size="mini" type="primary" @click="confirmStock">批量设置</button>
				</view>
			
				<!-- 产品列表（主表） -->
				<view style="margin-top: 0px;">
					<uni-table ref="tableOfProduct" :loading="detailLoading"
						border
						stripe 
						type="selection" 
						@selection-change="selectionChange"
						emptyText="暂无更多数据">
					<uni-tr style="background-color: #dbfbdb;">
						<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
						<uni-th align="left" width="40" style="font-size: 12px;color: #62c188;">产品编码</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">物料编码</uni-th>
						<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料名称</uni-th>
						<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料规格</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">应收数量</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">已入库数量</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">已退库数量</uni-th>
						<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">可入库数量</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">实收数量</uni-th>
						<uni-th align="left" width="130" style="font-size: 12px;color: #62c188;">入库仓库</uni-th>
						<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">批号</uni-th>
						<uni-th align="left" width="150" style="font-size: 12px;color: #62c188;">备注</uni-th>
					</uni-tr>
					<uni-tr v-for="(item, index) in workOrderList" :key="index">
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ index+1 }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.productCode }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomCode }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomName }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomStandard }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.maxPickingNum }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.hasInstockNum }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.hasReStockNum }}</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.availableInStockNum }}</uni-td>
						<uni-td align="left">
							  <uni-easyinput type="digit" 
								  v-model="item.todayRecvNum" 
								  @focus="currentRowSelected(item, index)"
								  @blur="todayRecvNumChange(item, index)"
								  @clear="clearRecvNum(item)"
								  placeholder="实收数量" />
						</uni-td>
						<uni-td align="left" style="font-size: 11px;text-align: left;">
							  <uni-easyinput type="text" 
								  v-model="item.stockIdReq" 
								  @clear="clearStockIdReq(item)"
								  @focus="stockInFocus(item, index)"
								  placeholder="选择入库仓库" />
						</uni-td>
						<uni-td align="left" style="font-size: 12px;text-align: left;">
							  <uni-easyinput type="text" 
								  v-model="item.lotReq" 
								  placeholder="选择输入批号" />
						</uni-td>
						<uni-td align="left" style="font-size: 11px;text-align: left;">
							<uni-easyinput type="text" v-model="item.remark" placeholder="输入备注" />
						</uni-td>
					</uni-tr>
					</uni-table>
				</view>
			</view>
		</view>
		
		<view v-if="this.workOrderList.length == 0" style="padding-top: 60px;">
			<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="loadingShow"></u-loading-icon>
			<u-empty mode="data" v-if="!loadingShow"></u-empty>
		</view>
		
		<!-- 库存列表数据 -->
		<uni-popup ref="stockPopup" :mask-click="false">
			<view class="content">
				<view class="itme-box">
					<view class="h-table" v-if="this.selectedBom!== null">
						<uni-section class="mb-10" title="物料详情`" :sub-title="`编码：${selectedBom.bomCode}\t名称：${selectedBom.bomName}\n规格：${selectedBom.bomStandard}`" type="line"></uni-section>
						<uni-section class="mb-10" :title="`仓库总数:${this.total} 条，可选择分页查看`" type="line"></uni-section>
					</view>
					
					<view style="margin-top: 2rpx;">
						<uni-table ref="table" :loading="realStockLoading"
							border
							stripe 
							type="selection" 
							@selection-change="selectionStockChange"
							emptyText="暂无更多数据">
						<uni-tr style="background-color: #dbfbdb;">
							<uni-th align="left" width="35" style="font-size: 12px;color: #62c188;">序号</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;" 
								filter-type="search" @filter-change="stockNamefilterChange" >仓库名称</uni-th>
							<uni-th align="left" width="90" style="font-size: 12px;color: #62c188;">仓库编码</uni-th>
							<uni-th align="left" width="120" style="font-size: 12px;color: #62c188;">使用组织</uni-th>
							<uni-th align="left" width="70" style="font-size: 12px;color: #62c188;">仓库负责人</uni-th>
							<uni-th align="left" width="100" style="font-size: 12px;color: #62c188;">仓位</uni-th>
						</uni-tr>
						
						<uni-tr v-for="(item, index) in realStockDetailList" :key="index">
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.index }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.stockName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.stockNumber }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.factoryName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.principalName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.stockLocName }}</uni-td>
						</uni-tr>
						</uni-table>
						<view style="padding-top: 20rpx;">
							<uni-pagination 
								prevText="前一页"
								nextText="下一页"
								:page-size="pageSize" 
								:current="pageCurrent" 
								:total="total"
								@change="pageChange"/>
						</view>
					</view>
				</view>
			
				<view style="margin: 6rpx;">
					<uni-row>
						<uni-col :span="12">
							<u-button
								type="primary"
								text="关闭"
								shape="circle" 
								customStyle="width: 240rpx;"
								@click="stockClose"
							></u-button>
						</uni-col>
						<uni-col :span="12">
							<u-button
								type="primary"
								text="确认"
								shape="circle" 
								customStyle="width: 240rpx;"
								@click="confirmStock"
							></u-button>
						</uni-col>
					</uni-row>
				</view>
			</view>
		</uni-popup>
		
		<!-- 点击选择产品 ，弹出产品类型选框，以下是依赖进来的控件 -->
		<u-popup
			:safeAreaInsetBottom="true"
			:safeAreaInsetTop="true"
			:mode="popupData.mode"
			:show="show"
			:round="popupData.round"
			:overlay="popupData.overlay"
			:borderRadius="popupData.borderRadius"
			:closeable="popupData.closeable"
			:closeOnClickOverlay="popupData.closeOnClickOverlay"
			@close="close"
			@open="open"
			customStyle="max-height: 100vh; overflow-y: auto; overflow-x: hidden;">
			<view
				class="u-popup-slot"
				:style="{
					width: '240px',
					marginTop: '20rpx',
				}">
				 <view style="margin-left: 5px;"><u--text text="选择产品:" type="info"></u--text></view>
				 <u-line></u-line>
				 <u-row customStyle="margin-bottom: 4px" v-for="(group, groupIndex) in groupedProductList" :key="groupIndex">
					<u-col span="6" v-for="(product, productIndex) in group" :key="product.productId">
						<u-tag :text="`${product.productName}`" 
						:plain="!product.checked" 
						type="warning" 
						:name="`${product.productId}`" 
						style="margin: 5px; white-space: normal; word-wrap: break-word;"
						@click="productSelected"></u-tag>
					</u-col>
					<!-- <u-col span="6">
						<u-tag :text="`选项1`" :plain="false" type="warning" :name="1" style="margin: 5px;"></u-tag>
					</u-col> -->
				</u-row>
				<u-row customStyle="margin-bottom: 4px; margin-top: 30px;" gutter="6" >
					<u-col span="6">						
						<u-button type="primary" @click="close" style="margin: 5px;">确认</u-button>
					</u-col>
					<u-col span="6">
						<!-- <u-tag :text="`选项1`" :plain="false" type="warning" :name="1" style="margin: 5px;"></u-tag> -->
						<u-button type="warning" @click="reset" style="margin-right: 5px;">重置</u-button>
					</u-col>
				</u-row>
			</view>
		</u-popup>
		<u-modal
			:content="submitContent"
			:show="submitInstockShow"
			showCancelButton
			closeOnClickOverlay
			@confirm="submitInstock"
			@cancel="() => submitInstockShow = false"
		></u-modal>
		<u-toast ref="uToast" duration="3000" />
		<!-- <u-toast ref="uToast2Success" duration="1000" /> -->
		<u-notify ref="uNotify"></u-notify>
		<uni-fab ref="fab" 
			:pattern="pattern" 
			:content="content" 
			:horizontal="horizontal" 
			:vertical="vertical"
			:direction="direction" 
			@trigger="trigger" 
			@fabClick="fabClick" />
	</view>
</template>

<script>
	
import FloatButton from '@/components/button/FloatButton'
import * as workorderApi from '@/api/order/workorder';
export default {
	components: {
		FloatButton,
	},
	data() {
		return {
			queryKey: "",
			trueValue: true,
			loadingShow: false,
			submitInstockShow: false,
			submitContent: '',
			workOrderList: [],
			allSubMaterialList: [],
			list1: [{
				name: '工单产品清单',
			}],
			productList: [
				// {productId: 1, productName: "血管造影导管（半成品）", checked: false},
				// {productId: 2, productName: "连通板（半成品）", checked: false},
				
			],
			groupedProductList: [],
			popupData: {
				overlay: true,
				mode: 'right',
				closeOnClickOverlay: true
			},
			show: false,
			radios: [
				{checked: true},
				{checked: false},
				{checked: false}
			],			
			value5: "",
			value: "",
			checked: ["选中"],
			// u-checkbox-group的v-model绑定的值如果设置为某个checkbox的name，就会被默认选中
			checkboxValue1: [],
			selectedCard: null, // 选中的卡片ID
			contractCode: null,
			orderCode: null,
			productCode: null,
			bomCode: null,
			action: null,
			orderType: null,
			status: null,
			
			detailLoading: false,
			realStockLoading: false,
			
			bomMaterialLoading: false,
			
			realStockDetailList: [],
			
			// 悬浮按钮开始
			pattern: {
				color: '#7A7E83',
				backgroundColor: '#fff',
				selectedColor: '#007AFF',
				buttonColor: '#007AFF',
				iconColor: '#fff',
				icon: 'gear'
			},
			content: [{
					iconPath: '/static/picking/refresh.png',
					selectedIconPath: '/static/picked/refresh.png',
					text: '刷新当前',
					active: false
				},{
					iconPath: '/static/picking/history.png',
					selectedIconPath: '/static/picking/history_selected.png',
					text: '入库记录',
					active: false
				},
				{
					iconPath: '/static/picking/doneall.png',
					selectedIconPath: '/static/picking/doneall_selected.png',
					text: '全部入库',
					active: false
				},
				{
					iconPath: '/static/picking/submit.png',
					selectedIconPath: '/static/picking/submit_selected.png',
					text: '提交入库',
					active: false
				}
			],
			horizontal: 'left',
			vertical: 'bottom',
			direction: 'vertical',
			// 悬浮按钮结束
			
			notifyData: {
				top: 4,
				message: 'notify顶部提示',
				type: 'warning',
				color: '#ffffff',
				bgColor: '',
				fontSize: 12,
				duration: 2500,
				safeAreaInsetTop: false
			},
			productSelectedList: [],
			productIndexList: [],
			
			stockSelected: null,
			stockSelectedStockNo: null,
			focusIndex: -1,
			isFirstLoad: false,
			
			// 每页数据量
			pageSize: 7,
			// 当前页
			pageCurrent: 1,
			// 数据总量
			total: 0,
			
			totalStockNum: 0,
			selectedBom: null,
			stockNameParam: null,
			lotParam: null,
		}
	},
	watch: {
		workOrderList(newVal, oldVal) {
			this.$nextTick(() => {
				console.log("workOrderList updated:", newVal);
				// 指定部分选中
				if (this.isFirstLoad) {
					// this.$refs.tableOfProduct.selectionAll();
					this.isFirstLoad = false;
				}
			});
		}
	},
	mounted() {
		//TODO
	},
	onLoad(options) {
		console.log("options:", options);
		if (options.contractCode) {
			this.queryKey = decodeURIComponent(options.contractCode);
		}
		if (options.action) {
			this.action = options.action;
		}
		if (options.orderType) {
			this.orderType = options.orderType;
		}
		if (options.status) {
			this.status = options.status;
		}
		if (options.bomCode) {
			this.bomCode = decodeURIComponent(options.bomCode);
		}
		if (options.contractCode && options.orderCode) {
			this.contractCode = decodeURIComponent(options.contractCode);
			this.orderCode = decodeURIComponent(options.orderCode);
			// this.productCode = decodeURIComponent(options.productCode);
			this.isFirstLoad = true;
		}
		console.log("bomCode:", this.bomCode, this.contractCode, this.orderCode);
		this.queryInstockDetailList();
	},
	methods: {
		selectionChange(e) {
			console.log("多选事件触发:", e);
			if (this.workOrderList.length === 0) {
				return;
			}
			this.productIndexList = [];
			for (let i of e.detail.index) {
			  const item = this.workOrderList[i];
			  if (item !== null && item !== undefined) {
				  this.productIndexList.push(i);
			  }
			}
		},
		selectionStockChange(e) {
			console.log("仓库页面单选事件发生:", e);
			if (e.detail.index.length === 0) {
				this.notifyError("仓库未选择，请重新选择");
				return;
			}
			if(e.detail.index.length>1) {
				this.$refs.table.toggleRowSelection([e.detail.index[0]], false);
			}
			if (this.realStockDetailList.length === e.detail.index[0]) {
				this.notifyError("最后一个不是有效仓库，请重新选择");
				return;
			}
			this.stockSelected = this.realStockDetailList[e.detail.index[0]];
			console.log("选择仓库:", this.stockSelected);
		},
		confirmStock() {
			console.log("选择仓库:", this.stockSelected);
			if (!this.stockSelected) {
				this.notifyError("未选择任何仓库，请选择复选框");
				return;
			}
			if (this.selectedBom) {
				this.selectedBom.stockIdReq = this.stockSelected.stockNumber;
				// this.selectedBom.lotReq = this.stockSelected.flotCode;
			} else {
				if (this.productIndexList.length === 0) {
					this.notifyError("未选择任何产品进行入库，请先关闭仓库页面去选择产品");
					return;
				}
				for (let i of this.productIndexList) {
					this.workOrderList[i].stockIdReq = this.stockSelected.stockNumber;
					// this.workOrderList[i].lotReq = this.stockSelected.flotCode;
				}
				this.stockSelectedStockNo = this.stockSelected.stockNumber;
			}
			this.stockClose();
		},
		queryByParam() {
			this.queryInstockDetailList();
		},
		returnChange(value, item) {
			console.log(value, item);
		},
		stockInFocus(item, index) {
			console.log("focus:", item);
			this.pageCurrent = 1;
			this.focusIndex = index;
			this.selectedBom = item;
			this.loadRealStockNumByBomCode();
		},
		notifyError(message) {
			this.notifyData.type = 'error';
			this.notifyData.message = message;
			this.$refs.uNotify.show({
				...this.notifyData
			});
		},
		notifySuccess(message) {
			this.notifyData.type = 'success';
			this.notifyData.message = message;
			this.$refs.uNotify.show({
				...this.notifyData
			});
		},
		notifyWarning(message) {
			this.notifyData.type = 'warning';
			this.notifyData.message = message;
			this.$refs.uNotify.show({
				...this.notifyData
			});
		},
		currentRowSelected(item, index, e) {
			console.log("index:", index);
			this.$refs.tableOfProduct.toggleRowSelection([index], true);
		},
		todayRecvNumChange(row, index, e) {
			if (!row.todayRecvNum) {
				return;
			}
			if (!(!isNaN(parseFloat(row.todayRecvNum)) && isFinite(row.todayRecvNum)) || row.todayRecvNum <= 0) {
				this.notifyError(`输入必须是大于 0 的数字`);
				return;
			}
			if (!row.availableInStockNum) {
				this.notifyError(`${row.bomCode}/${row.bomName}可入库数量为0，不能进行入库`);
				row.todayRecvNum = null;
				return;
			}
			if (Number(row.todayRecvNum) > row.availableInStockNum) {
				this.notifyError(`${row.bomCode}/${row.bomName}, 不能超过可入库数量:${row.availableInStockNum}`);
				row.todayRecvNum = row.availableInStockNum;
			}
		},
		ceilIfDecimal(number) {
		    // 判断是否是小数
		    return number % 1 !== 0 ? Math.ceil(number) : number;
		},
		clearRecvNum(row, e) {
			console.log("row->", row);
		},
		clearStockIdReq(row, e) {
			console.log("row->", row);
			row.lotReq = null;
		},
		// 处理关联数据结束
		queryInstockDetailList(call) {
			if (this.queryKey) {
				this.contractCode = this.queryKey;
			}
			
			this.bomMaterialLoading = true;
			workorderApi.queryInstockDetailByContractCodeV2({
				pageNum: 1, 
				pageSize: 2000, 
				orderCode: this.orderCode,
				contractCode: this.contractCode,
				productCode: this.productCode,
				bomCode: this.bomCode,
				queryKey: this.queryKey,
				action: this.action,
				orderType: this.orderType,
				status: this.status,
				productSelectedList: this.productSelectedList,
			}).then(res => {
				this.workOrderList = res.data.noMergeList || [];
				this.bomMaterialLoading = false;
				if (call) {
					call();
				}
								
			}).catch(err => {
				// 提交异常
				console.error("入库查询发生异常", err);
				this.bomMaterialLoading = false;
				this.workOrderList = [];
				if (call) {
					call();
				}
			});
		},
		submitInstockPreOfNoCheckAll() {
			if (this.workOrderList.length === 0) {
				this.notifyError(`产品清单为空，无法操作全部入库`);
				return;
			}
			for (let item of this.workOrderList) {
				if (item.availableInStockNum <= 0) {
					continue;
				}
				item.todayRecvNum = null;
				item.stockIdReq = null;
				item.lotReq = null;
			}
			this.$refs.tableOfProduct.clearSelection();
		},
		submitInstockPreOfAll() {
			if (this.workOrderList.length === 0) {
				this.notifyError(`产品清单为空，无法操作全部入库`);
				return;
			}
			for (let item of this.workOrderList) {
				if (item.availableInStockNum <= 0) {
					continue;
				}
				item.todayRecvNum = item.availableInStockNum;
			}
			this.$refs.tableOfProduct.selectionAll();
		},
		submitInstockPre() {
			if (!this.productIndexList || this.productIndexList.length == 0) {
				this.notifyError(`未选择任何选择产品，无法操作提交入库`);
				return;
			}
			let submitingList = this.workOrderList.filter(item => {
			  const recvNum = item.todayRecvNum ? Number(item.todayRecvNum) : 0;
			  return recvNum > 0 && item.stockIdReq;
			});
			if (submitingList.length === 0) {
				this.notifyError(`选择的产品未填写数量或未填写选择仓库，无法操作提交入库`);
				return;
			}
			
			let invalidateObj = null;
			let invalidateIndex = 0;
			for (let i of this.productIndexList) {
				let obj = this.workOrderList[i];
				if (!obj.stockIdReq) {
					invalidateObj = obj;
					invalidateIndex = i;
					break;
				}
			}
			if (invalidateObj) {
				this.notifyError(`选择的第 [${invalidateIndex+1}]产品 ${invalidateObj.bomCode}未填写数量或未填写选择仓库，无法操作提交入库`);
				return;
			}
			
			let cur = this.workOrderList[0];
			this.submitContent = `确认要提交批量入库请求吗？\n合同号:${cur.contractCode}\n入库产品种数：${submitingList.length} 种`;
			this.submitInstockShow = true;
		},
		submitInstock() {
			console.log('提交入库数据');
			
			if (this.productIndexList.length === 0) {
				this.notifyError(`您还未选择任何需要入库的产品信息，先选择产品`);
				return;
			}
			
			let cur = this.workOrderList[0];
			let bomSelectedList = [];
			for(let i of this.productIndexList) {
				let item = this.workOrderList[i];
				if (item.todayRecvNum && item.todayRecvNum > 0 && item.stockIdReq) {
					bomSelectedList.push(item);
				}
			}
			if (bomSelectedList.length === 0) {
				this.notifyError(`您还未选择任何需要入库的产品信息，先选择产品~`);
				return;
			}
			let submitParam = {
				contractCode: cur.contractCode,
				orderCode: cur.orderCode,
				bomSelectedList: bomSelectedList,
			};
			workorderApi.submitInstock(submitParam).then(res => {
				if (res.code == 200) {
					this.submitInstockShow = false;
					this.queryByParam();
				} else {
					this.notifyError(`提交失败,原因：${res.msg}`);
				}
			}).catch(err => {
				// 提交异常
				console.error("入库提交发生异常", err);
			});
		},
		groupedProducts() {
			const size = 2;
		      return this.productList.reduce((result, item, index) => {
		        const chunkIndex = Math.floor(index / size);
		        if (!result[chunkIndex]) {
		          result[chunkIndex] = [];
		        }
		        result[chunkIndex].push(item);
		        return result;
		      }, []);
		},
		productSelected(name){
			const found = this.productList.find(item => item.productId === Number(name));
			console.log("click", name, found);
			if (found) {
				found.checked = !found.checked;
			}
			for(let item of this.productList) {
				if(item.productId !== found.productId) {
					item.checked = false;
				}
			}
		},
		change(e) {
			console.log("onchange", e);
		},
		tabClick(item) {
			console.log('item', item);
			// uni.$u.sleep().then(() => {
			// 	this.show = !this.show
			// });
			// this.groupedProductList = this.groupedProducts();
		},
		floatOnclick() {
			console.log("float");
		},
		openOfCollapse(e) {
		  // console.log('open', e)
		},
		closeOfCollapse(e) {
		  // console.log('close', e)
		},
		changeOfCollapse(e) {
		  // console.log('change', e)
		},
		open() {
			// console.log('open');
			document.body.style.overflow = 'hidden'; // 禁用背景页面滚动
		},
		close() {
			this.show = false
			// console.log('close');
			document.body.style.overflow = ''; // 恢复背景页面滚动
		},
		reset() {
			for(let item of this.productList) {
				item.checked = false;
			}
		},
		load() {
			// dom 结构加载完毕时触发
			console.log("load finished");
		},
		ready() {
			// 渲染完毕时触发
			console.log("ready finished");
		},
		textConvert(label, value) {
			return `${label}: ${value}`;
		},
		textConvertOfObj(label, work) {
			if (work.hasPickingNum > 0 && work.hasPickingNum != work.maxPickingNum) {
				return `${label}: 部分入库`;
			}
			return `${label}: ${work.hasPickingNum}`;
		},
		stockClose() {
			this.stockNameParam = null;
			this.lotParam = null;
			this.selectedBom = null;
			this.$refs.stockPopup.close();
		},
		findIndexByStockNoAndFlotCode(stockNo, flotCode) {
		  return this.realStockDetailList.findIndex(item => 
		    item.stockNo === stockNo && item.flotCode === flotCode
		  );
		},
		stockNamefilterChange(e) {
			console.log("stockNamefilterChange", e);
			this.stockNameParam = e.filter;
			if (this.selectedBom) {
				this.loadRealStockNumByBomCode();
				return;
			}
			this.batchLoadStockList();
		},
		lotfilterChange(e) {
			console.log("lotfilterChange", e);
			this.lotParam = e.filter;
			if (this.selectedBom) {
				this.loadRealStockNumByBomCode();
				return;
			}
			this.batchLoadStockList();
		},
		batchLoadStockList() {
			this.selectedBom = null;
			this.totalStockNum = 0;
			let materilIdList = [];
			for (let oneBom of this.workOrderList) {
				materilIdList.push({supplyId: oneBom.factoryId, bomCode:oneBom.bomCode});
			}
			let queryParam = {
				pageCurrent: this.pageCurrent,
				pageSize: this.pageSize,
				orderType: "7",
				materilIdList: [],
				stockNameParam: this.stockNameParam,
				lotParam: this.lotParam,
			};
			workorderApi.getStockBaseList(queryParam).then(res => {
				if (res.code == 200) {
					this.realStockLoading = false;
					this.realStockDetailList = res.rows || [];
					this.total = res.total || 0;
					if (res.footer && res.footer.length >0 ) {
						this.totalStockNum = res.footer[0].totalStockNum;
					}
					this.$refs.stockPopup.open('top');
				} else {
					this.notifyError(`获取单个物料库存失败,原因：${res.msg}`);
				}
			}).catch(err => {
				// 提交异常
				console.error("获取单个物料库存发生异常", err);
			});
		},
		loadRealStockNumByBomCode() {
			if(!this.selectedBom) {
				this.notifyError(`未选择任何产品，请选择产品再操作`);
				return;
			}
			let materilIdList = [];
			for (let obj of this.workOrderList) {
				materilIdList.push({supplyId: obj.factoryId, bomCode:obj.bomCode});
			}
			this.totalStockNum = 0;
			let queryParam = {
				pageCurrent: this.pageCurrent,
				pageSize: this.pageSize,
				orderType: "7",
				materilIdList: [],
				stockNameParam: this.stockNameParam,
				lotParam: this.lotParam,
				// materilIdList: [{supplyId: oneBom.supplyId, bomCode:oneBom.bomCode}]
			};
			workorderApi.getStockBaseList(queryParam).then(res => {
				if (res.code == 200) {
					this.realStockLoading = false;
					this.realStockDetailList = res.rows || [];
					this.total = res.total || 0;
					if (res.footer && res.footer.length >0 ) {
						this.totalStockNum = res.footer[0].totalStockNum;
					}
					
					// 2 更新合计
					// const bomCodeMap = this.groupBomAndSumStoreNum(this.realStockDetailList);
					// let found = bomCodeMap.get(this.selectedBom.bomCode);
					// if (found) {
					// 	this.selectedBom.realStockNum = found;
					// } else {
					// 	this.selectedBom.realStockNum = "0";
					// }
					
					this.$refs.stockPopup.open('top');
					
					// 更新仓库页面被选中状态
					// if (this.selectedBom.stockIdReq && this.selectedBom.lotReq) {
					// 	this.$nextTick(() => {
					// 		const selIndex = this.findIndexByStockNoAndFlotCode(this.selectedBom.stockIdReq, this.selectedBom.lotReq);
					// 		console.log('selIndex:', selIndex);
					// 		if (selIndex >= 0) {
					// 			this.$refs.table.toggleRowSelection([selIndex], true);
					// 		}
					// 	});
					// }
				} else {
					this.notifyError(`获取单个物料库存失败,原因：${res.msg}`);
				}
			}).catch(err => {
				// 提交异常
				console.error("获取单个物料库存发生异常", err);
			});
		},
		pageChange(e) {
			this.pageCurrent = e.current;
			if (this.selectedBom) {
				this.loadRealStockNumByBomCode();
			} else {
				this.batchLoadStockList();
			}
		},
		groupBomAndSumStoreNum(data) {
		    const resultMap = new Map();
		    data.forEach(item => {
		        const { bomCode, storeNum } = item;
		
		        // 将storeNum转换为数字，如果为null或空字符串，则视为0
		        const value = storeNum ? Number(storeNum) : 0;
		
		        // 如果Map中已存在该bomCode，则累加storeNum
		        if (resultMap.has(bomCode)) {
					const currentSum = resultMap.get(bomCode);
					const newSum = (currentSum + value).toFixed(4);
					resultMap.set(bomCode, parseFloat(newSum));
		        } else {
		            // 否则初始化为当前storeNum值
		            resultMap.set(bomCode, parseFloat(value.toFixed(4)));
		        }
		    });
		
		    return resultMap;
		},
		trigger(e) {
			console.log(e);
			const btn = this.content[e.index];
			btn.active = true;
			if (btn.text === '刷新当前') {
				this.queryInstockDetailList(() => {
					btn.active = false;
				});
			} else if (btn.text === '入库记录') {
				const contractCode = encodeURIComponent(this.contractCode);
				this.navigateTo(`/pages/work/order/instockHistory?contractCode=${contractCode}`);
			} else if (btn.text === '全部入库') {
				this.submitInstockPreOfAll();
				btn.active = false;
				btn.text = "取消全部";
			} else if (btn.text === '取消全部') {
				this.submitInstockPreOfNoCheckAll();
				btn.active = true;
				btn.text = "全部入库";
			} else if (btn.text === '提交入库') {
				this.submitInstockPre();
			}
		},
		fabClick() {
			// uni.showToast({
			// 	title: '点击了悬浮按钮',
			// 	icon: 'none'
			// })
		},
		// 跳转到指定页面
		navigateTo (url) {
		  uni.navigateTo({ url: url })
		},
	}
}
</script>

<style lang="scss">
/* 引入表格样式表 */
@import "helang-table.scss";

.card-container{
	width: 100%;
	min-height: 100%;
	box-sizing: border-box;
	padding: 8rpx;
	background-color: #ECECEC;
}
.card-wrap{
	padding: 12rpx;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	.card-item{
		display: flex;
		align-items: center;
		font-size: 28rpx;
		padding-bottom: 20rpx;
		color: #111111;
	}
	.card-item-txt{
		flex:1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
.card-btns{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.card-btns uni-button {
  flex: 1;
  margin: 0 5px; /* 调整按钮间距 */
}
.card-wrap-selected {
  border-color: #007bff; /* 选中状态的边框颜色 */
  background-color: #e7f0ff; /* 选中状态的背景颜色 */
}

.demo-layout {
	// height: 25px;
	border-radius: 0px;
}
.bg-purple {
	background: #CED7E1;
}
.bg-purple-light {
	background: #e5e9f2;
}
.border-row {
  box-sizing: border-box; 
  border-top: 1px solid #dfe2e5; 
  border-left: 1px solid #dfe2e5;
  border-right: 1px solid #dfe2e5; 
  border-bottom: 0.2px solid #dfe2e5;
  padding: 8px;             /* 可选：内边距 */
}
/deep/ .u-collapse-item__content__text {
	padding: 2px 8px !important;
	color: #606266 !important;
	font-size: 14px !important;
	line-height: 18px !important;
}

.card-item-layout{
	border-radius: 6rpx;
	background-color: #FFF;
	// border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	align-items: left;
	font-size: 28rpx;
	color: #40485d;
}

.card-item-single{
	border-radius: 6rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	align-items: left;
	font-size: 30rpx;
	color: #40485d;
}

.float-button {
  position: fixed;
  bottom: 6px;
  left: 50%;
  // width: 52px;
  // height: 52px;
  // transform: translateX(-50%);
  z-index: 10;
}
.float-button-right {
  position: fixed;
  bottom: 6px;
  right: 50%;
  // width: 52px;
  // height: 52px;
  // transform: translateX(-50%);
  z-index: 10;
}


/* 示例样式开始 */
.content {
	font-size: 28rpx;
	background-color: #f3f3f3;
	padding: 10rpx;
	
	.red{
		background-color: #DD524D;
		color: #fff;
		text-align: center;
	}
	
	.green{
		background-color: #42b983;
		color: #fff;
		text-align: center;
	}
	
	.blue{
		background-color: #007AFF;
		color: #fff;
		text-align: center;
	}
	
	.yellow{
		background-color: #ffaa00;
		color: #fff;
		text-align: center;
	}
	

	.itme-box {
		padding: 10rpx;
		background-color: #fff;
		margin-bottom: 10rpx;

		.title {
			padding-bottom: 12rpx;
			margin-bottom: 12rpx;
			border-bottom: #e5e5e5 solid 1px;
			line-height: normal;
		}
		
		// .width-fill{
		// 	width: 100%;
		// }
		
		.preview-box{
			height: 400rpx;
			box-shadow: 0 0 4px rgba(0,0,0,0.3);
		}
	}
}
/* 示例样式结束 */

.td_header {
	color: rgb(98, 193, 136);
	background-color: #dbfbdb;
}
</style>
